import { getUrls } from "../utils/constants";
import axios, { AxiosError } from "axios";
import {
  CreateAnalysisParams,
  ListWorkspacesResponse,
  ListAnalysesResponse,
  CreateAnalysisResponse,
  GetAnalysisSummaryParams,
  GetAnalysisSummaryResponse,
  GetStatementDetailsParams,
  GetStatementDetailsResponse,
  ValidationResult,
  ValidationOptions,
} from "../types/apiTypes";

import { handleAxiosError } from "../utils/errorHandler";

export const getWorkspaces = async (
  userKey: string
): Promise<ListWorkspacesResponse> => {
  try {
    const { DOMAIN } = getUrls();
    const url = `${DOMAIN.Backend}/api/v1/listWorkspaces`;
    const response = await axios.post<ListWorkspacesResponse>(url, {
      userKey,
      pageSize: 100,
      pageNumber: 1,
    });

    if (!response.data.data) {
      throw new Error("error.backendUrl.invalid");
    }
    return response.data;
  } catch (error) {
    throw handleAxiosError(error as AxiosError, "工作空间列表获取");
  }
};

export const getAnalyses = async (
  userKey: string,
  workspaceId: string
): Promise<ListAnalysesResponse> => {
  try {
    const { DOMAIN } = getUrls();
    const url = `${DOMAIN.Backend}/api/v1/listAnalyses`;
    const response = await axios.post<ListAnalysesResponse>(url, {
      userKey,
      workspaceId,
      pageSize: 10,
      pageNumber: 1,
    });

    if (!response.data.data) {
      throw new Error("error.backendUrl.invalid");
    }
    return response.data;
  } catch (error) {
    throw handleAxiosError(error as AxiosError, "优化列表获取");
  }
};

export const createAnalysis = async (
  params: CreateAnalysisParams
): Promise<CreateAnalysisResponse> => {
  try {
    const { DOMAIN } = getUrls();
    const url = `${DOMAIN.Backend}/api/v1/createAnalysis`;
    const response = await axios.post<CreateAnalysisResponse>(url, params);

    if (!response.data.data) {
      throw new Error("error.backendUrl.invalid");
    }

    if (!response.data.data.status.startsWith("success")) {
      throw new Error("error.create.analysis.failed");
    }

    return response.data;
  } catch (error) {
    throw handleAxiosError(error as AxiosError, "优化任务创建");
  }
};

export const getAnalysisSummary = async (
  params: GetAnalysisSummaryParams
): Promise<GetAnalysisSummaryResponse> => {
  try {
    const { DOMAIN } = getUrls();
    const url = `${DOMAIN.Backend}/api/v1/getAnalysisSummary`;
    const response = await axios.post<GetAnalysisSummaryResponse>(url, params);

    if (!response.data.data) {
      throw new Error("error.backendUrl.invalid");
    }
    return response.data;
  } catch (error) {
    throw handleAxiosError(error as AxiosError, "优化概要获取");
  }
};

export const getStatementDetails = async (
  params: GetStatementDetailsParams
): Promise<GetStatementDetailsResponse> => {
  try {
    const { DOMAIN } = getUrls();
    const url = `${DOMAIN.Backend}/api/v1/getStatementDetails`;
    const response = await axios.post<GetStatementDetailsResponse>(url, params);

    if (!response.data.data) {
      throw new Error("error.backendUrl.invalid");
    }
    return response.data;
  } catch (error) {
    throw handleAxiosError(error as AxiosError, "优化详情获取");
  }
};

export const validateUserKey = async (userKey: string): Promise<boolean> => {
  try {
    const { DOMAIN } = getUrls();
    const url = `${DOMAIN.Backend}/api/v1/validateUserKey`;
    const response = await axios.post(url, { userKey });
    return response.data.code === 200;
  } catch (error) {
    console.error("UserKey 验证失败:", error);
    return false;
  }
};

export const getUserKey = async (
  backendUrl: string,
  email: string,
  password: string
): Promise<{ apikey: string; frontendUrl: string } | null> => {
  try {
    const url = `${backendUrl}/api/v1/getUserKey`;
    console.log(url);

    const response = await axios.post(url, { email, password });
    return response.data.data;
  } catch (error) {
    console.error("获取用户密钥失败:", error);
    return null;
  }
};

export const validateBackend = async (
  backendUrl: string,
  options: ValidationOptions = {}
): Promise<ValidationResult> => {
  try {
    const url = backendUrl.endsWith("/") ? backendUrl.slice(0, -1) : backendUrl;
    const response = await axios({
      method: "get",
      url: url,
      headers: { Accept: "application/json, text/plain, */*" },
      validateStatus: (status) => status >= 200 && status < 500,
    });

    const isSuccessResponse = response.status >= 200 && response.status < 400;
    return {
      isAvailable: true,
      details: {
        message: isSuccessResponse
          ? `成功连接到后端服务 (状态码: ${response.status})`
          : `后端服务可访问，但返回了状态码: ${response.status}`,
        statusCode: response.status,
      },
    };
  } catch (error) {
    return handleAxiosError(error as AxiosError, "后端");
  }
};

export const validateFrontend = async (
  frontendUrl: string,
  options: ValidationOptions = {}
): Promise<ValidationResult> => {
  const timeout = options.timeout || 5000;
  const defaultCheckPaths = ["/favicon.ico", "/robots.txt", "/"];
  const baseUrl = frontendUrl.endsWith("/")
    ? frontendUrl.slice(0, -1)
    : frontendUrl;
  const checkPaths = options.checkPaths || defaultCheckPaths;

  const checkUrl = async (path: string): Promise<ValidationResult> => {
    try {
      const response = await axios({
        method: "head",
        url: `${baseUrl}${path}`,
        timeout,
        headers: { Accept: "text/html, */*" },
        maxRedirects: 3,
        validateStatus: (status) => status >= 200 && status < 500,
      });

      const isSuccessResponse = response.status >= 200 && response.status < 400;
      return {
        isAvailable: true,
        details: {
          message: isSuccessResponse
            ? `成功连接到前端服务 (状态码: ${response.status})`
            : `前端服务可访问，但返回了状态码: ${response.status}`,
          statusCode: response.status,
        },
      };
    } catch (error) {
      return handleAxiosError(error as AxiosError, "前端");
    }
  };

  const results = await Promise.all(checkPaths.map((path) => checkUrl(path)));
  const successResult = results.find((r) => r.isAvailable);
  return successResult || results[results.length - 1];
};

export const ApiService = {
  getWorkspaces,
  getAnalyses,
  createAnalysis,
  getAnalysisSummary,
  getStatementDetails,
  validateUserKey,
  getUserKey,
  validateBackend,
  validateFrontend,
};
